// ARDIEx1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "SOCK_WrapperFacade.h"
#include "Thread_Manager.h"

#define DEFAULT_PORT 27015

void *client_handler(void *arg) {
	
	SOCKET h = reinterpret_cast <SOCKET> (arg);
	char buffer[500];

	printf("Client handler started\n");
	SOCK_Stream stream(h);

	memset(buffer, 0, sizeof(buffer));
	size_t n = stream.recv_n(buffer, sizeof(buffer), 0);
	if (n > 0) printf(buffer);

	printf("Client handler ended\n");
	return 0;
}

int main(int argc, char* argv[])
{

	unsigned long address = 0x7F000001;
	// Convert server address to hexadecimal base.
	if (argc > 1) {
		printf("Server set as %s\n", argv[1]);
		address = ntohl(inet_addr(argv[1]));
	} else
		printf("Server set as localhost\n");

	// On windows start socket 2.2 system
	WSADATA wsa_data;
	WORD version_requested = MAKEWORD(2, 2);
	int error = WSAStartup(version_requested, &wsa_data);
	if (error != 0) return -1;

	Thread_Manager threadManager;
	INET_Addr addr(DEFAULT_PORT, address);
	SOCK_Acceptor server(addr); 
	SOCK_Stream new_stream;

	for (;;) {
		printf("Server started waiting for connection\n");
		server.accepting(new_stream);
		SOCKET h = new_stream.get_handle();

		// Spawn off a thread-per-connection
		threadManager.spawn(client_handler, reinterpret_cast<void *> (h), 0); 
	}

	WSACleanup();
	return 0;
}

